#include "drawwidget.h"

DrawWidget::DrawWidget(QWidget *parent)
    : QWidget{parent}
{
    setAutoFillBackground (true); //对窗体背景色的设置
    setPalette(QPalette(Qt::white));
    pix =new QPixmap (size()); //此 QPixmap 对象用千准备随时接收绘制的内容
    pix->fill(Qt::white); //填充背景色为白色
    setMinimumSize(600,400); //设置绘制区窗体的最小尺寸
}

void DrawWidget::setStyle(int s)
{
    style = s;
}

void DrawWidget::setWidth(int w)
{
    weight = w;
}

void DrawWidget::setColor(QColor c)
{
    color = c;
}

void DrawWidget::clear()
{
    QPixmap *clearPix =new QPixmap (size());
    clearPix->fill(Qt::white);
    pix= clearPix;
    update();
}

void DrawWidget::mousePressEvent(QMouseEvent *event)
{
    startPos = event->pos();
}

void DrawWidget::mouseMoveEvent(QMouseEvent *event)
{
    QPainter painter;
    QPen pen;
    pen. setStyle((Qt::PenStyle)style);
    pen.setWidth(weight);
    pen.setColor(color);
    painter.begin(pix);
    painter.setPen(pen);
    //绘制从 startPos 到鼠标当前位置的直线
    painter.drawLine(startPos, event->pos ());
    painter.end();
    startPos =event->pos();
    update();
}

void DrawWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(QPoint(0,0),*pix);
}

void DrawWidget::resizeEvent(QResizeEvent *event)
{
    if(height()>pix->height()||width()>pix->width())
    {
        QPixmap *newPix = new QPixmap(size());
        newPix->fill(Qt::white);
        QPainter p(newPix);

        //缩放函数有返回值，需要接受才能改变
        //*pix=pix->scaled(size());
        p.drawPixmap(QPoint(0,0),*pix);
        pix = newPix;
    }
    QWidget::resizeEvent(event);
}
